package realtime.app.dws;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import realtime.app.func.BeanToJsonStrFunction;
import realtime.app.func.DimAsyncFunction;
import realtime.beans.ExamPaperBean;
import realtime.util.DateFormatUtil;
import realtime.util.DorisUtil;
import realtime.util.EnvUtil;
import realtime.util.KafkaUtil;

import java.util.concurrent.TimeUnit;

public class DwsExamPaperWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = EnvUtil.getSEE(4);
        String topic = "dwd_exam_paper";
        String groupId = "dws_exam_paper_window_group";
        KafkaSource<String> kafkaSource = KafkaUtil.getKafkaConsumer(topic, groupId);
        DataStreamSource<String> kafkaStrDS = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafka_source");
        //将流中数据转换为jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObj = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context ctx, Collector<JSONObject> out) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                        out.collect(jsonObject);
                    }
                }
        );
        //指定水位线
        SingleOutputStreamOperator<JSONObject> watermarkDS = jsonObj.assignTimestampsAndWatermarks(
                WatermarkStrategy.<JSONObject>forMonotonousTimestamps()
                        .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject jsonObject, long l) {
                                return jsonObject.getLong("ts") * 1000;
                            }
                        })
        );
        //按照试卷分组
        KeyedStream<JSONObject, String> keyedDS = watermarkDS.keyBy(v1 -> v1.getString("paper_id"));
        //对流中数据进行处理并封装为实体类
        SingleOutputStreamOperator<ExamPaperBean> processDS = keyedDS.process(
                new ProcessFunction<JSONObject, ExamPaperBean>() {
                    @Override
                    public void processElement(JSONObject jsonObj, ProcessFunction<JSONObject, ExamPaperBean>.Context ctx, Collector<ExamPaperBean> out) throws Exception {
                        String paperId = jsonObj.getString("paper_id");
                        Long score = jsonObj.getLong("score");
                        Long durationSec = jsonObj.getLong("duration_sec");
                        ExamPaperBean examPaperBean = new ExamPaperBean(
                                "",
                                "",
                                "",
                                paperId,
                                "",
                                1L,
                                score,
                                durationSec
                        );
                        out.collect(examPaperBean);
                    }
                }
        );
        //按照试卷分组
        KeyedStream<ExamPaperBean, String> paperKeyedDS = processDS.keyBy(v1 -> v1.getPaperId());
        //开窗
        WindowedStream<ExamPaperBean, String, TimeWindow> windowDS = paperKeyedDS.window(TumblingEventTimeWindows.of(Time.seconds(10)));
        //聚合
        SingleOutputStreamOperator<ExamPaperBean> reduceDS = windowDS.reduce(
                new ReduceFunction<ExamPaperBean>() {
                    @Override
                    public ExamPaperBean reduce(ExamPaperBean v1, ExamPaperBean v2) throws Exception {
                        v1.setExamUserCt(v1.getExamUserCt() + v2.getExamUserCt());
                        v1.setScore(v1.getScore() + v2.getScore());
                        v1.setDurTime(v1.getDurTime() + v2.getDurTime());
                        return v1;
                    }
                }, new WindowFunction<ExamPaperBean, ExamPaperBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<ExamPaperBean> input, Collector<ExamPaperBean> out) throws Exception {
                        String stt = DateFormatUtil.toYmdHms(window.getStart());
                        String edt = DateFormatUtil.toYmdHms(window.getEnd());
                        String curDate = DateFormatUtil.toDate(window.getStart());
                        for (ExamPaperBean examPaperBean : input) {
                            examPaperBean.setStt(stt);
                            examPaperBean.setEdt(edt);
                            examPaperBean.setCurDate(edt);
                            out.collect(examPaperBean);
                        }
                    }
                }
        );
        //补充维度字段 paper_title
        SingleOutputStreamOperator<ExamPaperBean> resultDS = AsyncDataStream.unorderedWait(
                reduceDS,
                new DimAsyncFunction<ExamPaperBean>("dim_test_paper") {
                    @Override
                    public String getKey(ExamPaperBean bean) {
                        return bean.getPaperId();
                    }

                    @Override
                    public void join(ExamPaperBean bean, JSONObject dim) {
                        bean.setPaperTitle(dim.getString("paper_title"));
                    }
                },
                60,
                TimeUnit.SECONDS
        );
        resultDS.print(">>>>");
        resultDS.map(
                new BeanToJsonStrFunction<>()
        ).sinkTo(
                DorisUtil.getDorisSink("dws_exam_paper_window")
        );
        env.execute();
    }
}
